import { useState, useEffect, useCallback, useRef } from 'react';
import webSocketManager from './WebSocketManager.js';
import { ConnectionStatus } from './types.js';

/**
 * WebSocket React Hook
 * 提供便捷的WebSocket连接状态管理和消息处理
 * @param {Object} options 配置选项
 * @param {Function} options.onMessage 消息处理回调
 * @param {Function} options.onStatusChange 状态变化回调
 * @param {boolean} options.autoConnect 是否自动连接
 * @returns {Object} WebSocket状态和方法
 */
const useWebSocket = (options = {}) => {
  const {
    onMessage = null,
    onStatusChange = null,
    autoConnect = true
  } = options;

  const [status, setStatus] = useState(webSocketManager.getStatus());
  const [reconnectAttempts, setReconnectAttempts] = useState(webSocketManager.getReconnectAttempts());
  const [lastMessage, setLastMessage] = useState(null);
  const [error, setError] = useState(null);

  const onMessageRef = useRef(onMessage);
  const onStatusChangeRef = useRef(onStatusChange);

  // 更新refs
  useEffect(() => {
    onMessageRef.current = onMessage;
    onStatusChangeRef.current = onStatusChange;
  }, [onMessage, onStatusChange]);

  // 处理状态变化
  const handleStatusChange = useCallback((newStatus) => {
    setStatus(newStatus);
    setReconnectAttempts(webSocketManager.getReconnectAttempts());
    
    if (newStatus === ConnectionStatus.ERROR) {
      setError('WebSocket连接错误');
    } else {
      setError(null);
    }

    if (onStatusChangeRef.current) {
      onStatusChangeRef.current(newStatus);
    }
  }, []);

  // 处理接收到的消息
  const handleMessage = useCallback((message, manager) => {
    setLastMessage(message);
    
    if (onMessageRef.current) {
      onMessageRef.current(message, manager);
    }
  }, []);

  // 注册消息处理器
  useEffect(() => {
    // 注册状态变化回调
    webSocketManager.onStatusChange(handleStatusChange);

    // 注册通用消息处理器（用于更新lastMessage）
    // 使用通配符 '*' 来注册一个处理所有消息类型的通用处理器
    webSocketManager.registerHandler('*', handleMessage);

    return () => {
      // 清理：移除状态变化回调
      // 注意：消息处理器不需要清理，因为它们是单例的
    };
  }, [handleStatusChange, handleMessage]);

  // 自动连接（只在组件挂载时执行一次）
  useEffect(() => {
    if (autoConnect && status === ConnectionStatus.DISCONNECTED) {
      connect();
    }
  }, [autoConnect]); // 移除status依赖，避免状态变化触发重复连接

  /**
   * 连接WebSocket
   * @returns {Promise<boolean>} 连接是否成功
   */
  const connect = useCallback(async () => {
    setError(null);
    return await webSocketManager.connect();
  }, []);

  /**
   * 断开WebSocket连接
   */
  const disconnect = useCallback(() => {
    webSocketManager.disconnect();
  }, []);

  /**
   * 发送消息
   * @param {string} type 消息类型
   * @param {Object} data 消息数据
   * @returns {boolean} 发送是否成功
   */
  const sendMessage = useCallback((type, data) => {
    import('./types.js').then(({ WebSocketMessage }) => {
      const message = new WebSocketMessage(type, data);
      return webSocketManager.sendMessage(message);
    }).catch(error => {
      console.error('发送消息失败:', error);
      return false;
    });
  }, []);

  /**
   * 注册自定义消息处理器
   * @param {string} messageType 消息类型
   * @param {Function} handler 处理器函数
   */
  const registerHandler = useCallback((messageType, handler) => {
    webSocketManager.registerHandler(messageType, handler);
  }, []);

  /**
   * 清除最后一条消息
   */
  const clearLastMessage = useCallback(() => {
    setLastMessage(null);
  }, []);

  /**
   * 清除错误
   */
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  return {
    // 状态
    status,
    reconnectAttempts,
    lastMessage,
    error,
    isConnected: status === ConnectionStatus.CONNECTED,
    isConnecting: status === ConnectionStatus.CONNECTING,
    isReconnecting: status === ConnectionStatus.RECONNECTING,
    isDisconnected: status === ConnectionStatus.DISCONNECTED,
    hasError: status === ConnectionStatus.ERROR,
    
    // 方法
    connect,
    disconnect,
    sendMessage,
    registerHandler,
    clearLastMessage,
    clearError,
    
    // 管理器实例（高级用法）
    manager: webSocketManager
  };
};

export default useWebSocket;
export { ConnectionStatus };
